﻿using System;
using System.Linq;
using Structures.Model;
using Xtensive.Orm;
using Xtensive.Orm.Configuration;

namespace Structures
{
    public class Program
    {
        public static void Main()
        {
            // Loading domain configuration section with name "Default".
            var domainConfiguration = DomainConfiguration.Load("Default");
            var domain = Domain.Build(domainConfiguration);

            using (var session = domain.OpenSession()) {
                using (var tx = session.OpenTransaction()) {

                    var google = new Company(session);
                    google.Name = "Google Inc.";

                    // No need to create instance of Address type
                    // DataObjects.Net creates it on first access to Company.Address field
                    google.Address.Country = "USA";
                    google.Address.State = "CA";

                    // Company.Address acts like a proxy, it updates underlying fields in 'google' object
                    var address = google.Address;
                    address.City = "Mountain View";
                    address.Street1 = "1600 Amphitheatre Parkway";
                    address.Zip = "94043";

                    PrintCompany(google);

                    // Value of Company.Address field can be copied to another Company instance
                    var froogle = new Company(session) {
                        Name = "Froogle Inc.",
                        Address = google.Address
                    };

                    PrintCompany(froogle);

                    // Structures can be used in queries
                    Console.WriteLine("\n * Using structures in queries");
                    var companies = session.Query.All<Company>()
                        .Where(c => c.Address.State == "CA").ToList();
                    foreach (var company in companies)
                        PrintCompany(company);

                    tx.Complete();
                }
            }
        }

        private static void PrintCompany(Company company)
        {
            Console.WriteLine("Company: {0}, {1} {2}, {3} {4} {5}", company.Name, company.Address.Street1, company.Address.City, company.Address.State, company.Address.Zip, company.Address.Country);            
        }
    }
}